<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\helpers\ArrayHelper;
use kartik\widgets\SwitchInput;
use yii\helpers\Url;
use kartik\widgets\DateTimePicker;
use yii\widgets\ActiveForm;
use backend\models\match\MatchPlan;
use kartik\file\FileInput;
use yii\bootstrap\Modal;
use kartik\widgets\DatePicker;

/* @var $this yii\web\View */
/* @var $searchModel backend\models\messages\MessageSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
/* @var $model backend\models\messages\Message */

$matchDefaultTitle = [
        '赛程安排通知' => '赛程安排通知',
        '赛事紧急取消通知' => '赛事紧急取消通知',
    ];
?>
<div class="match-message-index">

    <p>
        <?= Html::a('添加信息推送', '#', [
            'id' => 'create-message',
            'data-toggle' => 'modal',
            'data-target' => '#create-message-modal',
            'class' => 'btn btn-success',
        ]);
        ?>
    </p>
    <?php Pjax::begin(); ?>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
//        'filterModel' => $searchModel,
        'columns' => [
//            ['class' => 'yii\grid\SerialColumn'],
            'title',
//            'content',
            [
                'attribute' => 'user_ids',
                'format' => 'raw',
                'value' => function ($model) {
                    return Html::a('查看用户列表', '#', [
                        'class' => 'btn btn-info btn-xs get-user-list',
                        'data-toggle' => 'modal',
                        'data-title' => '查看用户列表',
                        'data-target' => '#user-modal',
                        'data-message' => $model->user_ids,
                    ]);
                }
            ],
            [
                'attribute' => 'receive_port',
                'format' => 'raw',
                'filter' => $searchModel->receivePort,
                'value' => function ($model) {
                    $data = $model->setPort($model->receive_port, true);
                    return implode(',', $data);
                }
            ],
            [
                'attribute' => 'details_link',
                'format' => 'raw',
                'value' => function ($model) {
                    if (!empty($model->details_link)) {
                        return Html::a('查看详情', $model->details_link, ['target' => '_blank', 'data-pjax' => 0]);
                    }
                }
            ],
            [
                'attribute' => 'push_at',
                'format' => ['date', 'php:Y-m-d H:i'],
                'filter' => DatePicker::widget([
                    'model' => $searchModel,
                    'attribute' => 'push_at',
                    'pluginOptions' => [
                        'autoclose' => true,
                        'format' => 'yyyy-mm-dd'
                    ]
                ]),
            ],
            [
                'attribute' => 'created_at',
                'format' => ['date', 'php:Y-m-d H:i'],
                'filter' => DatePicker::widget([
                    'model' => $searchModel,
                    'attribute' => 'created_at',
                    'pluginOptions' => [
                        'autoclose' => true,
                        'format' => 'yyyy-mm-dd'
                    ]
                ]),
            ],
            [
                'attribute' => 'status',
                'value' => function ($model) {
                    if ($model->status == 1) {
                        return Html::tag('span', Yii::t('app', '推送完毕'), ['class' => 'label label-primary']);
                    } else {
                        return Html::decode(SwitchInput::widget([
                            'name' => '',
                            'value' => $model->status,
                            'pluginOptions' => [
//                                'size' => 'mini',
                                'onText' => '停止',
                                'offText' => '等待',
                                'onColor' => 'danger',
//                                'offColor' => 'danger',
                            ],
                            'options' => [
                                'class' => 'switch',
                                'data-id' => $model->id,
                                'data-link' => Url::to(['messages/message']),
                            ]
                        ]));

                    }
                },
                'format' => 'raw',
                'filter' => [
                    0 => Yii::t('app', '等待推送'),
                    1 => Yii::t('app', '推送完毕'),
                    2 => Yii::t('app', '停止推送'),
                ]
            ],
//            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
    <?php Pjax::end(); ?>


    <?php
    Modal::begin([
        'id' => 'user-modal',
        'header' => '<h4 class="modal-title">用户列表</h4>',
        'footer' => '<a href="#" class="btn btn-primary" data-dismiss="modal">关闭</a>',
    ]);

    echo Html::tag('div', Html::tag('div', '', ['class' => 'user-message']), ['class' => 'row']);


    $js = <<<JS
$(function() {
    $('.get-user-list').on('click',function() {
        
        var str = $(this).attr('data-message');
        var html;
        if (str) {
           var arr = str.split(',');
           html = "<table class='table'>";
           html += '<thead><th>用户ID<th></thead>';
           html += '<tbody>';
           for (var i = 0; i < arr.length; i++) {
               html += '<tr><td>' + arr[i] + '<td><tr>';
           }
           html += '</tbody>';
           html += '</table>';
        }else{
            html = null;
        }
        $('#user-modal').find('.user-message').html(null)
        .end()
        .find('.user-message').html(html);
    });
});
JS;
    $this->registerJs($js);
    Modal::end();
    ?>

    <?php
    Modal::begin([
        'id' => 'create-message-modal',
        'header' => '<h4 class="modal-title">创建</h4>',
        'footer' => \yii\bootstrap\Alert::widget([
            'options' => [
                'class' => ['alert-info', 'text-left']
            ],
            'body' => "<p>说明：</p>
                        <p>优先选择自定义接收人员。</p>
                        <p>自定义消息类型无需填写项目ID，其他项目类型请填写项目ID。</p>
                        <p>接收端为公众号时微信模版与微信内容必填，回车换行为下一行内容。<a href='https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277' class='text-danger' target='_blank'>详见</a></p>
                        <p>推送时间为空时为实时推送。</p>
                        <p>自定义接收人格式为.xls,.xlsx，内容只获取第二列第四行(包含)之后数据。</p>",
        ]),
    ]);
    echo Html::beginTag('div', ['class' => 'row']);
    $form = ActiveForm::begin([
        'action' => ['messages/message/create-match-js'],
        'id' => 'message-form-save',
        'enableAjaxValidation' => true,
        'validationUrl' => Url::toRoute(['messages/message/validate-match-form-js']),
    ]);

    $message = Html::label('接收目标', ['class' => 'control-label']);
    $message .= Html::dropDownList(
        'MatchPlanID',
        null,
        ArrayHelper::map(MatchPlan::find()->where(['match_id' => $searchModel->item_id])->all(), 'id', 'counter_num'),
        ['class' => 'form-control', 'prompt' => '赛事局数']
    );
    $message .= $form->field($model, 'receive_port')->checkboxList($model->receivePort, ['class' => 'form-control']);

    $message .= $form->field($model,'title')->dropDownList($matchDefaultTitle);
    $message .= $form->field($model, 'content')->textarea(['rows' => 6]);

    echo Html::tag('div', $message, ['class' => 'col-sm-6']);


    $message = $form->field($model, 'push_at')->widget(DateTimePicker::class, [
        'options' => ['placeholder' => ''],
        'readonly' => true,
        'pluginOptions' => [
            'autoclose' => true,
            'format' => 'yyyy-mm-dd hh:ii',
            'startDate' => date('Y-m-d H:i'),
        ]
    ]);

    $message .= $form->field($model, 'wechat_template')->dropDownList(ArrayHelper::map($templates, 'template_id', 'title'), ['prompt' => '--请选择公众号模版类型--']);
    $message .= $form->field($model, 'wechat_content')->textarea(['rows' => 6]);
    $message .= $form->field($model, 'details_link')->textInput(['maxlength' => true]);

    echo Html::tag('div', $message, ['class' => 'col-sm-6']);

    $message = Html::label('自定义接收人');
    $message .= FileInput::widget([
        'model' => $model,
        'attribute' => 'file',
        'options' => [
            'accept' => '.xls,.xlsx',
            'multiple' => true
        ],
        'pluginOptions' => [
            'showPreview' => false,
            'uploadUrl' => Url::to(['messages/message/upload-file'], true),
            'maxFileCount' => 1,
            'uploadExtraData' => [
                'dir' => strtolower($model->formName()),
                'file' => 'file',
            ],
            'uploadAsync' => true,
        ],
        'pluginEvents' => [
            "fileuploaded" => "function (event, data, id, index) {   
                                            console.log(data);
                                            $(\"input[name='Message[file_path]']\").val(data.response.data.link);
                                        }",
        ],
    ]);
    $message .= $form->field($model, 'file_path')->hiddenInput()->label(false);
    $message .= $form->field($model, 'item_id')->label(false)->hiddenInput(['value' => $searchModel->item_id]);
    $message .= $form->field($model, 'class')->label(false)->hiddenInput(['value' => $searchModel->class]);
    $message .= Html::hiddenInput('wechat_content_len');

    $message .= Html::tag('div', Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']), ['class' => 'form-group']);

    echo Html::tag('div', $message, ['class' => 'col-sm-12']);

    ActiveForm::end();

    echo Html::endTag('div');

    Modal::end();

    $obj = json_encode($templates);

    $js = <<<JS
$(function ($) {
     
    var obj = $obj;
    
    $(document).on('change', '#message-wechat_template', function () {
        templateMessage();
    });
    $(document).ready(function() {
        templateMessage();
    });
    
    function templateMessage() {
        var template = $('#message-wechat_template');
        if (obj[template.val()]) {
            var len = obj[template.val()]['content'].split('\\n').length;
            $('input[name="wechat_content_len"]').val(len);
            $('#message-wechat_content').attr('placeholder',obj[template.val()]['content']);
        }else{
            $('#message-wechat_content').attr('placeholder','标题\\r\\n内容1\\r\\n内容2\\r\\n内容3\\r\\n...\\r\\n备注');
            $('input[name="wechat_content_len"]').val(null);
        }
    }
    
    $(document).on('beforeSubmit', 'form#message-form-save', function () {
        var form = $(this);
        //返回错误的表单信息
        if (form.find('.has-error').length) {
            return false;
        }
        
        $.post(
            form.attr('action'),
            form.serialize(),
            function (response) {
                console.log(response);
                    alert(response.message);
                if (response.result === 'success') {
                    window.location.reload();
                }
                return false;
            },
            // 'json'
        );
        return false;
    });
});
JS;
    $this->registerJs($js);
    ?>
</div>
